from django.core.cache import cache
from django.utils import timezone
from .models import Order, Review
from accounts.models import Technician
from .serializers import OrderSerializer, ReviewSerializer

class OrderService:
    """订单业务逻辑服务类"""
    
    @staticmethod
    def get_orders_for_user(user):
        """根据用户角色获取订单列表"""
        cache_key = f"order_list_{user.id}_{user.role}"
        
        # 尝试从缓存获取数据
        cached_data = cache.get(cache_key)
        if cached_data:
            return cached_data
        
        if user.role == 'customer':
            orders = Order.objects.filter(customer=user)
        elif user.role == 'technician':
            try:
                technician = user.technician_profile
                orders = Order.objects.filter(technician=technician)
            except Technician.DoesNotExist:
                raise PermissionError('您不是认证技师')
        else:  # admin
            orders = Order.objects.all()
        
        serializer = OrderSerializer(orders, many=True)
        
        # 将数据存入缓存，缓存10分钟
        cache.set(cache_key, serializer.data, 600)
        
        return serializer.data
    
    @staticmethod
    def get_order_detail(order_id, user):
        """获取订单详情"""
        # 尝试从缓存获取数据
        cache_key = f"order_detail_{order_id}_{user.id}"
        cached_data = cache.get(cache_key)
        if cached_data:
            return cached_data
        
        try:
            order = Order.objects.get(id=order_id)
        except Order.DoesNotExist:
            raise ValueError('订单不存在')
        
        # 权限检查
        if user.role == 'customer' and order.customer != user:
            raise PermissionError('无权查看此订单')
        
        if user.role == 'technician':
            try:
                technician = user.technician_profile
                if order.technician != technician:
                    raise PermissionError('无权查看此订单')
            except Technician.DoesNotExist:
                raise PermissionError('您不是认证技师')
        
        serializer = OrderSerializer(order)
        
        # 将数据存入缓存，缓存5分钟
        cache.set(cache_key, serializer.data, 300)
        
        return serializer.data
    
    @staticmethod
    def create_order(data, customer):
        """创建订单"""
        if customer.role != 'customer':
            raise PermissionError('只有顾客可以创建订单')
        
        # 创建订单
        order = Order.objects.create(
            customer=customer,
            technician_id=data['technician'],
            service_id=data['service'],
            appointment_time=data['appointment_time'],
            address=data['address'],
            contact_person=data['contact_person'],
            contact_phone=data['contact_phone'],
            remarks=data.get('remarks', ''),
            original_price=data.get('original_price', 0),
            discount=data.get('discount', 0),
            final_price=data.get('final_price', 0)
        )
        
        # 设置默认价格
        if not order.original_price:
            order.original_price = order.service.price
        if not order.final_price:
            order.final_price = order.original_price - order.discount
        order.save()
        
        # 清除缓存
        cache.delete(f"order_list_{customer.id}_customer")
        
        serializer = OrderSerializer(order)
        return serializer.data
    
    @staticmethod
    def accept_order(order_id, technician_user):
        """技师接单"""
        if technician_user.role != 'technician':
            raise PermissionError('只有技师可以接单')
        
        try:
            technician = technician_user.technician_profile
            order = Order.objects.get(id=order_id, technician=technician, status='created')
        except Order.DoesNotExist:
            raise ValueError('订单不存在或无权操作')
        except Technician.DoesNotExist:
            raise PermissionError('您不是认证技师')
        
        # 更新订单状态
        order.status = 'accepted'
        order.save()
        
        # 清除相关缓存
        cache.delete(f"order_detail_{order_id}_{technician_user.id}")
        cache.delete(f"order_list_{order.customer.id}_customer")
        cache.delete(f"order_list_{technician_user.id}_technician")
        
        serializer = OrderSerializer(order)
        return serializer.data
    
    @staticmethod
    def cancel_order(order_id, user):
        """取消订单"""
        try:
            order = Order.objects.get(id=order_id)
        except Order.DoesNotExist:
            raise ValueError('订单不存在')
        
        # 权限检查
        if user.role == 'customer' and order.customer != user:
            raise PermissionError('无权操作此订单')
        
        if user.role == 'technician':
            try:
                technician = user.technician_profile
                if order.technician != technician:
                    raise PermissionError('无权操作此订单')
            except Technician.DoesNotExist:
                raise PermissionError('您不是认证技师')
        
        # 只有在特定状态下才能取消订单
        if order.status not in ['created', 'accepted']:
            raise ValueError('当前订单状态无法取消')
        
        order.status = 'cancelled'
        order.save()
        
        # 清除相关缓存
        cache.delete(f"order_detail_{order_id}_{user.id}")
        cache.delete(f"order_list_{order.customer.id}_customer")
        if hasattr(order.technician, 'user'):
            cache.delete(f"order_list_{order.technician.user.id}_technician")
        
        serializer = OrderSerializer(order)
        return serializer.data
    
    @staticmethod
    def complete_order(order_id, technician_user):
        """完成订单"""
        if technician_user.role != 'technician':
            raise PermissionError('只有技师可以完成订单')
        
        try:
            technician = technician_user.technician_profile
            order = Order.objects.get(id=order_id, technician=technician, status='in_service')
        except Order.DoesNotExist:
            raise ValueError('订单不存在或无权操作')
        except Technician.DoesNotExist:
            raise PermissionError('您不是认证技师')
        
        # 更新订单状态
        order.status = 'completed'
        order.completed_at = timezone.now()
        order.save()
        
        # 清除相关缓存
        cache.delete(f"order_detail_{order_id}_{technician_user.id}")
        cache.delete(f"order_list_{order.customer.id}_customer")
        cache.delete(f"order_list_{technician_user.id}_technician")
        
        serializer = OrderSerializer(order)
        return serializer.data
    
    @staticmethod
    def add_review(order_id, data, customer):
        """添加评价"""
        if customer.role != 'customer':
            raise PermissionError('只有顾客可以评价')
        
        try:
            order = Order.objects.get(id=order_id, customer=customer, status='completed')
        except Order.DoesNotExist:
            raise ValueError('订单不存在或无权评价')
        
        # 检查是否已评价
        if hasattr(order, 'review'):
            raise ValueError('订单已评价')
        
        # 创建评价
        review = Review.objects.create(
            order=order,
            customer=customer,
            technician=order.technician,
            rating=data['rating'],
            comment=data['comment'],
            is_anonymous=data.get('is_anonymous', False)
        )
        
        # 更新技师评分
        technician = order.technician
        total_reviews = technician.reviews.count()
        if total_reviews > 0:
            total_rating = sum([r.rating for r in technician.reviews.all()])
            technician.rating = total_rating / total_reviews
        else:
            technician.rating = review.rating
        technician.save()
        
        # 清除相关缓存
        cache.delete(f"order_detail_{order_id}_{customer.id}")
        cache.delete(f"order_list_{customer.id}_customer")
        cache.delete(f"order_list_{technician.user.id}_technician")
        
        serializer = ReviewSerializer(review)
        return serializer.data